<template>
  <div class="dynamic-form">
    <page-box>
      <template #top>
        <alert-msg
          content="动态表单模版可以用来在呼叫、会话、客户联络等场景下记录服务内容，支持使用自定义字段组建不同的动态表单模板，应用于各种服务场景"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #table>
        <resize-table :headers="tableHeaders" :data="tableData" :showPagination="false">
          <template #status="{ scope }">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="enable(scope.row)"
              inline-prompt
            />
          </template>
          <template #oprate="{ scope }">
            <span class="btn" @click="editTemp(scope.row)">编辑</span>
          </template>
        </resize-table>
      </template>
    </page-box>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import resizeTable from '@/common/components/resize-table/index.vue'
import alertMsg from '@common/components/alert/index.vue'
import { getList, updateTemplate } from '@app/base/apis/dynamic-form'
import { useRouter } from 'vue-router'
import { commonStore } from '@/common/store/modules/common'
import mcCache from '@/common/utils/mc-get-cache'
import pageBox from '@common/components/page-box.vue'
interface State {
  tableHeaders: Record<string, unknown>[]
  tableData: Record<string, unknown>[]
  scenesOptions: Record<string, unknown>
  init: boolean
}

const $router = useRouter()

const state: State = reactive({
  tableHeaders: [
    { label: '模版名称', prop: 'name', show: true },
    { label: '模版描述', prop: 'description', show: true },
    { label: '应用场景', prop: 'scenesName', show: true },
    { label: '包含字段', prop: 'fieldNames', show: true },
    { label: '状态', prop: 'status', show: true, custom: true },
    { label: '操作', prop: 'oprate', show: true }
  ],
  tableData: [],
  scenesOptions: {
    callCenter: '呼叫中心',
    customerMgmt: '客户管理'
  },
  init: true
})

// pinia中获取数据
const globalFieldsObj: any = computed(() => {
  return commonStore().publicCache.globalFieldCacheObj || {}
})

// 编辑
const editTemp = (row: any) => {
  $router.push(`/account/dynamic_form/edit_temp?id=${row._id}`)
}

// 启用、停用
const enable = (item: any) => {
  if (state.init) {
    state.init = false
    return
  }
  ElMessageBox.confirm(`请确认是否${item.status ? '启用' : '停用'}该模版？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const sendData = {
        _id: item._id,
        status: item.status
      }
      updateTemplate(sendData).then((res) => {
        if (res.success) {
          ElMessage.success('操作成功')
          getData()
          // 更新pinia
          mcCache.$updateCacheBySingleKey(
            'dyForm',
            {
              _id: item._id,
              key: 'status',
              value: item.status
            },
            '_id',
            ''
          )
        }
      })
    })
    .catch(() => {
      getData()
    })
}

// 获取场景名称
const getScenes = (scenes: any) => {
  const scenesArr = scenes.map((v: string) => {
    return state.scenesOptions[v]
  })
  return scenesArr.join('、')
}

// 获取包含字段名称
const getFields = (fields: any) => {
  const fieldsArr = fields.map((v: any) => {
    const obj = globalFieldsObj.value[v.field]
    if (obj) {
      return obj.name
    }
  })
  return fieldsArr.join('、')
}

const getData = () => {
  getList().then((res) => {
    if (res.success && res.data) {
      res.data.forEach((item: any) => {
        // 场景处理
        if (item.scenes && item.scenes.length) {
          item.scenesName = getScenes(item.scenes)
        }
        // 包含字段处理
        if (item.fields && item.fields.length) {
          item.fieldNames = getFields(item.fields)
        }
      })
      state.tableData = res.data || []
    }
  })
}

onMounted(async () => {
  await mcCache.$getCache('globalFieldCache', 'hasObj', '', '', '', '', 'field') // 全局字段
  getData()
})

const { tableHeaders, tableData } = toRefs(state)
</script>

<style lang="stylus">
.dynamic-form
  height calc(100% - 48px)
  .mb-24
    margin-bottom 0
  .btn
    color var(--mc-main-color)
    cursor pointer
    margin-right 16px
    &:last-child
      margin-right 0px
</style>
